import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { DataService } from '../../../services/data.service';
import { StepbarService } from '../stepbar/stepbar.service';
import { otoRequireFile } from '../../../../assets/config/filerequire';
import * as _ from 'lodash'
@Component({
  selector: 'onetoone-stepbar',
  templateUrl: './stepbar.component.html',
  styleUrls: ['./stepbar.component.scss'],
  providers: [StepbarService]

})
export class OnetooneStepbarComponent implements OnInit {

  // 获取附件数据
  public fileData: any;

  // 获取基础信息
  public singleProductData: any;

  // 获取路由oprerate字段
  public oprerate: any;
  // 存放提示信息
  public requireTips: any = [];

  // 存放提示信息字符串
  public requireFinalTips: any;

  // 存放提示信息字符串
  public requireFinalPdfTips: any;

  // 存放提示信息字符串
  public requireFinalWordTips: any;

  // 存放未上传pdf提示信息
  public requirePdfTips: any = [];

  // 存放未上传word提示信息
  public requireWordTips: any = [];

  // filerequired的返回值
  public fileReturnValue: any;

  public step: any;

  // 获取路由nFundNo字段（内码）
  public nFundNo: any;

  // 获取路由index字段
  public pageIndex: any;

  // 状态条子数据数组
  public subStepCollection = [];
  public stepBarData: any = [];

  constructor(
    public dataService: DataService,
    public stepbarService: StepbarService,
    private route: ActivatedRoute,
    public router: Router
  ) {
    this.route.params.subscribe((data) => {
      this.nFundNo = data.nFundNo;
      this.pageIndex = data.index;
      this.oprerate = data.oprerate;
      if(this.pageIndex!='zh'){
          // 加载状态条
        this.loadStatusTree();
      }

    })
  }
  // 校验文件是否已经上传
  fileRequired() {
    let that = this;
    let getBody = {
      "sFundType": 3,
      "nFundNo": this.nFundNo
    }
    this.stepbarService.getFileTree(getBody).subscribe((data) => {
      if (data) {
        this.requirePdfTips = [];
        this.requireTips = [];
        this.requireWordTips = [];

        this.fileData = data.subTree
        // 获取配置文件
        let requireFile = otoRequireFile.requireFile;
        // 存放要求上传的类别
        let requireType: any = [];
        // 校验是否有上传
        _.forEach(requireFile, (item) => {
          requireType.push(item.sAttachType);
        })

        _.forEach(requireType, (item, index) => {
          _.forEach(this.fileData, (it, index) => {
            _.forEach(it.subTree, (i, index) => {
              if (item == i.sAttachType) {
                if (i.fileList[0].nAttachNo == null) {
                  this.requireTips.push(item);
                }
              }
            })
          })
        })

        // 校验pdf
        // 获取配置文件
        let requirePdfFile = otoRequireFile.requirePdfAndWord;
        // 存放要求上传的类别
        let requirePdfType: any = [];
        // 存放切出来的附件后缀
        let rawPdfFormat: any = [];

        _.forEach(requirePdfFile, (item, index) => {
          _.forEach(this.fileData, (it, index) => {
            _.forEach(it.subTree, (i, index) => {
              if (item.sAttachType == i.sAttachType) {
                if (i.fileList[0].nAttachNo !== null) {
                  rawPdfFormat = [];
                  _.forEach(i.fileList, (f, idx) => {
                    // 切后缀放进数组
                    // 附件名长度
                    let len = f.sAttachName.length;
                    // 最后一个.的位置
                    let lastDotIndex = f.sAttachName.lastIndexOf(".");
                    let index;
                    let fileType = f.sAttachName.substring(lastDotIndex + 1, len + 1);
                    rawPdfFormat.push(fileType);
                  })
                  if (_.includes(rawPdfFormat, 'pdf') !== true) {
                    //  没有该格式
                    this.requirePdfTips.push(item.sAttachType);
                  }

                } else {
                  // 如果没附件的话，加提示。
                  this.requirePdfTips.push(item.sAttachType);
                }
              }
            })
          })
        })

        // 校验word
        // 获取配置文件
        let requireWordFile = otoRequireFile.requirePdfAndWord;
        // 存放要求上传的类别
        let requireWordType: any = [];
        // 存放切出来的附件后缀
        let rawWordFormat: any = [];
        _.forEach(requireWordFile, (item, index) => {
          _.forEach(this.fileData, (it, index) => {
            _.forEach(it.subTree, (i, index) => {
              if (item.sAttachType == i.sAttachType) {
                if (i.fileList[0].nAttachNo !== null) {
                  rawWordFormat = [];
                  _.forEach(i.fileList, (f, idx) => {
                    // 切后缀放进数组
                    // 附件名长度
                    let len = f.sAttachName.length;
                    // 最后一个.的位置
                    let lastDotIndex = f.sAttachName.lastIndexOf(".");
                    let index;
                    let fileType = f.sAttachName.substring(lastDotIndex + 1, len + 1);
                    rawWordFormat.push(fileType);
                  })
                  if (_.includes(rawWordFormat, 'docx') !== true&&_.includes(rawWordFormat, 'doc') !== true) {
                    //  没有该格式
                    this.requireWordTips.push(item.sAttachType);
                  }
                }
                else {
                  // 如果没附件的话，加提示。
                  this.requireWordTips.push(item.sAttachType);
                }
              }
            })
          })
        })

        // 优化提示信息：
        this.requireFinalTips = '';
        this.requireFinalPdfTips = '';
        this.requireFinalWordTips = '';
        if (this.requireTips.length !== 0) {
          this.requireFinalTips = '请上传：'+this.requireTips.join('、') + '文件；'
        }
        if (this.requirePdfTips.length !== 0) {
          this.requireFinalPdfTips = '请上传：'+this.requirePdfTips.join('、')+ '的pdf格式文件；'
        }
        if (this.requireWordTips.length !== 0) {
          this.requireFinalWordTips = '请上传：'+this.requireWordTips.join('、') + '的word格式文件；'
        }
        if (this.requireTips.length == 0 && this.requirePdfTips.length == 0 && this.requireWordTips.length == 0) {


          this.fileReturnValue = true;
        }
        else {

          this.fileReturnValue = false;
        }
      }
    })

  }

  changeLabel(subStep) {
    let that = this;
    let maxSubStep;
    let maxSubStepCollection = [];
    _.forEach(this.stepBarData, function (item, index) {
      // 判断
      if (subStep.sParentCode == item.sStatusCode) {
        _.forEach(item.subTree, (it, idx) => {
          if (it.isCheck == 1) {
            maxSubStepCollection.push(it.nOrderId)
          }
        })
      }
      maxSubStep = _.max(maxSubStepCollection);
    })
    // 如果标蓝的最后一个子状态和点击的是同一个
    if (maxSubStep == subStep.nOrderId) {
      window['swal']("警告", "该步骤已标记，请不要重复标记", "warning")
    } else {
      window['swal']({
        title: "确认?",
        text: "是否确认切换到  " + subStep.sStatus + '  状态',
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "rgb(30,185,225)",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: true

      }, function (isConfirm) {
        if (isConfirm) {
          _.forEach(that.stepBarData, (item, index) => {
            _.forEach(item.subTree, (idx, i) => {
              if (subStep.sStatus == '基金业协会备案' && idx.sStatus == '基金业协会备案') {
                that.fileRequired();
                setTimeout(() => {
                  if (that.fileReturnValue == true) {
                    idx.isCheck = 1;
                  } else if (that.fileReturnValue == false) {
                    setTimeout(() => {
                      window['swal']({
                        title: "提示",
                        text: that.requireFinalPdfTips + '<br>'+that.requireFinalWordTips + '<br>'+that.requireFinalTips + '<br>上传完以上文件，产品才能切换到已成立状态',
                        html: true,
                        type:"warning"
                      });
                    }, 1000)
                  }
                }, 1000)
              } else {
                if (idx.sParentCode == subStep.sParentCode) {
                  if (idx.nOrderId > subStep.nOrderId) {
                    idx.isCheck = 0;
                  }
                  else if (idx.nOrderId < subStep.nOrderId) {
                    idx.isCheck = 1;
                  }
                  else if (idx.nOrderId == subStep.nOrderId) {
                    idx.isCheck = 1;
                  }

                }
              }
            })
          })
          setTimeout(() => {
            that.alterStatusTree();
          }, 1000)
        }

      })

    }

  }

  changeStep(ParentStep) {
    let that = this;
    // 存放除被点击的父状态以外的其他父状态
    let StepCollection = [];
    // 存放当前已标蓝的父状态
    let parIsChecked = [];

    _.forEach(that.stepBarData, function (item, index) {
      StepCollection.push(item.nOrderId);
    })
    _.forEach(that.stepBarData, function (item, index) {
      if (item.isCheck == 1) {
        parIsChecked.push(item.nOrderId);
      }
    })

    let maxParIsChecked = _.max(parIsChecked);
    var maxParIsCheckedIndex = parIsChecked.findIndex(function (value, index, arr) {
      return value == maxParIsChecked;
    });

    if (maxParIsChecked >= 5 && ParentStep.nOrderId <= 5) {
      window['swal']("提示", this.stepBarData[maxParIsCheckedIndex].sStatus + "状态不能回退！", "warning")
      return false;
    } else {
      let clickIndex = StepCollection.findIndex(function (value, index, arr) {
        return value == ParentStep.nOrderId;
      });
      StepCollection.splice(clickIndex, 1);
      if (Math.abs(ParentStep.nOrderId - maxParIsChecked) === 1) {
        /* 如果新点击的步骤在原来最大的步骤之前，要除去原来最大步骤的颜色 */
        if (maxParIsChecked > ParentStep.nOrderId) {
          window['swal']({
            "customClass": "product-detail-sweetalert",
            title: "确认?",
            text: "请确认是否回退到" + ParentStep.sStatus + '状态？当前子状态将清空标蓝！',
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "rgb(30,185,225)",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: true
          },
            function () {
              that.stepBarData[maxParIsCheckedIndex].isCheck = 0;
              // 回滚时清空上一个步骤的子状态
              _.forEach(that.stepBarData[maxParIsCheckedIndex].subTree, function (item, index) {
                item.isCheck = 0;
              })
              ParentStep.isCheck = 1;
              that.step = ParentStep.nOrderId;
              that.alterStatusTree();
            });
        }
        else {
          let that = this;
          // 如果点击‘起始运作’阶段，需校验起始运作日期
          if (ParentStep.nOrderId == '6') {
            // 如果起始运作日期不为空，允许切换
            that.stepbarService.otoGetSingleProduct(that.nFundNo).subscribe((data) => {
              if (data) {
                that.singleProductData = data
                if (that.singleProductData.dBegin!==''&&that.singleProductData.dBegin!==null) {
                  window['swal']({
                    title: "确认?",
                    text: "请确认是否切换到" + ParentStep.sStatus + '状态？',
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "rgb(30,185,225)",
                    confirmButtonText: "确认",
                    cancelButtonText: "取消",
                    closeOnConfirm: true
                  },
                    function () {
                      ParentStep.isCheck = 1;
                      that.step = ParentStep.nOrderId;
                      that.alterStatusTree();
                    });
                } else {
                  // 如果起始运作日期为空，弹出提示框
                  window['swal']("提示", "起始运作日期为空，不能切换到起始运作阶段", "warning")

                }
              }
            })

          } else {
            window['swal']({
              title: "确认?",
              text: "请确认是否切换到" + ParentStep.sStatus + '状态？',
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "rgb(30,185,225)",
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              closeOnConfirm: true
            },
              function () {
                ParentStep.isCheck = 1;
                that.step = ParentStep.nOrderId;
                that.alterStatusTree();
              });
          }
        }

      } else {
        // 如果点了相同步骤
        if (ParentStep.nOrderId == maxParIsChecked) {
            window['swal']({
              type: "warning",
              title: "提示",
              text: "当前状态已是" + ParentStep.sStatus + "状态，不需要切换。",
              closeOnConfirm: true,
              showConfirmButton: true
            });
        } else if (ParentStep.nOrderId > maxParIsChecked) {
          // 跳了后面的步骤
            window['swal']({
              type: "warning",
              title: "提示",
              text: "请先切换到" + that.stepBarData[maxParIsCheckedIndex + 1].sStatus + "阶段！",
              closeOnConfirm: true,
              showConfirmButton: true
            });
        }
        else if (ParentStep.nOrderId < maxParIsChecked) {
          // 跳了前面的步骤
            window['swal']({
              type: "warning",
              title: "",
              text: "请先回退到" + that.stepBarData[maxParIsCheckedIndex - 1].sStatus + "阶段！",
              closeOnConfirm: true,
              showConfirmButton: true
            });
        }
      }
    }
  }

  // 调用修改状态树接口
  alterStatusTree() {
    var that = this;
    // 存放当前已标蓝的父状态
    let parIsChecked = [];
    that.subStepCollection = [];
    _.forEach(this.stepBarData, function (item, index) {
      if (item.isCheck == 1) {
        parIsChecked.push(item.nOrderId);
      }
      _.forEach(item.subTree, function (it, index) {
        if (it.isCheck == 1) {
          that.subStepCollection.push(it.sStatusCode);
        }
      })
    })
    let maxParIsChecked = _.max(parIsChecked);
    var maxParIsCheckedIndex = parIsChecked.findIndex(function (value, index, arr) {
      return value == maxParIsChecked;
    });
    var maxParIsCheckedStatusCode = this.stepBarData[maxParIsCheckedIndex].sStatusCode;
    var putBody = {
      "nFundNo": this.nFundNo,
      "sStatus": maxParIsCheckedStatusCode,
      "sSubStatus": _.last(this.subStepCollection),
      "sSubStatusSets": this.subStepCollection
    }
    this.stepbarService.alterTree(putBody).subscribe(data => {
      // if (data) {
      //   // console.info(data);
      // }
    })
  }

  ngOnInit() {
    let that = this;
  }

  // 获取状态树
  loadStatusTree() {
    let pageIndex = this.pageIndex;
    this.stepBarData = [];
    var getBody = {
      "nFundNo": this.nFundNo
    }
    this.stepbarService.list(getBody).subscribe(data => {
      if (data) {
        //根据未成立、已成立、已终止加载不同数量的步骤。
        switch (pageIndex) {
          case "wcl":
            this.stepBarData = [];
            _.forEach(data.subTree, (item, index) => {
              let indexInt = parseInt(index);
              if (indexInt <= 4) {
                this.stepBarData.push(item);
              }
            })
            break;
          case "yclwyz":
            this.stepBarData = [];
            _.forEach(data.subTree, (item, index) => {
              let indexInt = parseInt(index);
              if (indexInt <= 5) {
                this.stepBarData.push(item);
              }
            })
            break;
          case "yclyyz":
            this.stepBarData = [];
            _.forEach(data.subTree, (item, index) => {
              let indexInt = parseInt(index);
              if (indexInt <= 5) {
                this.stepBarData.push(item);
              }
            })
            break;
        }

        // 获取当前最后已选中父步骤
        var lastParCollection = [];

        _.forEach(this.stepBarData, function (item, index) {
          if (item.isCheck == 1) {
            lastParCollection.push(item.nOrderId);
          }
        })
        var lastParChecked = _.max(lastParCollection);
        this.step = lastParChecked;
      }
    })
  }
}
